// pages/EditProductInfo/EditProductInfo.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    LabelItems: [
      { 'data_Item': '首次9.8折', "state": 0 },
      { 'data_Item': '设施齐全', "state": 0 },
      { 'data_Item': '环境优雅', "state": 0 },
      { 'data_Item': '味道纯正', "state": 0 },
      { 'data_Item': '首次9.8折', "state": 0 },
      { 'data_Item': '面包甜点', "state": 0 },
      { 'data_Item': '干净卫生', "state": 0 },
      { 'data_Item': '最多六个字啊', "state": 0 },
    ],
    type: 0,
    typeList:[],
    imgs: [],
    index:"",
    ishidden:false,
    list: '',
    upload_picture_list: [],
    showModal:false,
    LabelNew:'',//添加产品标签
    status:'',//判断状态
    goods_name:'',//名字
    category_id:'',//产品id
    retail_price:'',//零售价
    favoured_price:"",//优惠价
    unit:'',//单位
    desc:'',//描述
    tag_ids:[],
  },
  bindPickerChange: function (e) {
    console.log(e)
    let that = this;
    that.setData({
      index: e.detail.value,
      category_id: that.data.typeList[e.detail.value].id,
      ishidden: true
    })
    
  },
  radioChange: function (e) {
    this.setData({ type: e.detail.value })

  },
 
  // 点击保存
  shows(msg){
    wx.showToast({
      title: msg,
    })
  },
  formSubmit(e){
    let that = this;
    let form = e.detail.value;
    
    const reg = /(^[0-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
    console.log(form.is_on_sale)
    if (!form.goods_name) {
      that.shows("请输入产品名称")
      return;
    }
    if (!that.data.category_id) {
      that.shows("请选择产品分类")
      return;
    }
    if (!form.retail_price) {
      that.shows("请输入零售价")
      return;
    }
    if (!reg.test(form.retail_price)) {
      that.shows("请输入正确零售价")
      return;
    }
    if (!form.favoured_price) {
      that.shows("请输入优惠售价")
      return;
    }
    if (!reg.test(form.favoured_price)) {
      that.shows("请输入正确优惠售价")
      return;
    }
    if (!form.unit) {
      that.shows("请输入单位")
      return;
    }
    let postData = {
      category_id: that.data.category_id,
      goods_images: that.data.imgs,
      tag_ids: that.data.tag_ids,
      ...form
    }
    app.post("/goods/add", "post", postData).then(res => {
      console.log(res)
      that.shows(res.msg)
      setTimeout(function () {
        wx.navigateBack({
          delta: -1
        });
      }, 500)
    })
  },
  select_item1: function (e) {
    let that = this;
    
    var index = e.currentTarget.dataset.key;
    if (this.data.LabelItems[index].state == 1) {
      this.data.LabelItems[index].state = 0;
      that.data.tag_ids.splice(index,1)
      // console.log(that.data.tag_ids)
    } else if (this.data.LabelItems[index].state === 0) {
      var num = 0;
      that.data.tag_ids.push(this.data.LabelItems[index].id)
      // console.log(that.data.tag_ids)
      for (var i = 0; i < this.data.LabelItems.length; i++) {
        if (this.data.LabelItems[i].state === 1) {
          num++;
          
        }
      }
      if (num < 5) {
        this.data.LabelItems[index].state = 1;
        // console.log(that.data.tag_ids)
      } else {
        wx.showToast({
          title: '最多可选择5个',
          icon: 'none',
          duration: 2000
        })
      }
      
    }
    this.setData({
      LabelItems: this.data.LabelItems
    });
  },
  //选择图片方法
  uploadpic: function (e) {
    let that = this; //获取上下文
    let upload_picture_list = that.data.upload_picture_list;
    //选择图片
    wx.chooseImage({
      count: 8, // 默认9，这里显示一次选择相册的图片数量 
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        wx.uploadFile({
          url: 'https://api.51huijingang.com/api/merchant/upload', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: "file",
          success: function (data) {
            var datas = JSON.parse(data.data);
            console.log(datas)
            var datass = datas.url;
            imgs.push(datass);
            upload_picture_list.push(datass);
            that.setData({
              imgs: imgs,
              upload_picture_list: upload_picture_list
            });
          }
        })
      }
      // sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      // sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      // success: function (res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片 
      //   let tempFiles = res.tempFiles
      //   //把选择的图片 添加到集合里
      //   for (let i in tempFiles) {
      //     // tempFiles[i]['upload_percent'] = 0
      //     // tempFiles[i]['path_server'] = ''
      //     upload_picture_list.push(tempFiles[i]);
      //     tempImgs.push(tempFiles[i].path);
      //   }
      //   //显示
      //   that.setData({
      //     upload_picture_list: upload_picture_list,
      //     imgs:tempImgs
      //   });
      // }
    })
  },
  // 点击删除图片
  deleteImg: function (e) {
    let upload_picture_list = this.data.upload_picture_list;
    let index = e.currentTarget.dataset.index;
    upload_picture_list.splice(index, 1);
    this.setData({
      upload_picture_list: upload_picture_list
    });
  },
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  // deleteImg(e) {
  //   let upload_picture_list = this.data.upload_picture_list;
  //   let index = e.currentTarget.dataset.index;
  //   upload_picture_list.splice(index, 1);
  //   this.setData({
  //     upload_picture_list: upload_picture_list
  //   });
  // },
  // 删除产品标签
  DelLabel(e){
    let that = this;
    let id = e.currentTarget.dataset.id;
    app.post("/goods/del_tag","DELETE",{id:id}).then(res =>{
      wx.showToast({
        title: res.msg,
      })
      that.labelList(that.data.status)
    })
   
  },
  listenerNewLabelInput:function(e){
    this.data.LabelNew = e.detail.value;
  },
  AddLabel(e){
    let that = this;
    // let customLabel = this.data.LabelItems;
    if (that.data.LabelNew != ''){
      // var itemLabel = { 'data_Item': this.data.LabelNew, "state": 0 }
      // customLabel.push(itemLabel);
      app.post("/goods/add_tag", "post", { pid: that.data.status, name: that.data.LabelNew}).then(res =>{
        console.log(res);
        wx.showToast({
          title: res.msg,
        })
        that.labelList(that.data.status)
      })
    }
    // customLabel.splice(index, 1);
    // this.setData({
    //   LabelItems: customLabel
    // });
    
  },
  
  OpenModal:function(e){
    this.setData({
      showModal: true
    })
  },
  closeModal:function(e){
    this.setData({
      showModal:false
    })
  },
  FootSave: function () {
    wx.navigateTo({
      url: '../index2/index2',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({status:options.status});
    that.labelList(that.data.status);
    app.post("/category/goods_type","get",{id:that.data.status}).then(res =>{
      that.setData({typeList:res})
    })
  },
  // 标签类表
  labelList(id){
    let that = this;
    app.post("/category/goods_tag", "get", { id:id}).then(res => {
      console.log(res);
      res.forEach(function (v, i) {
        res[i].state = 0;
      })
      that.setData({ LabelItems: res })
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    var src = e.currentTarget.dataset.src;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: src,
      //所有图片
      urls: this.data.imgs
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})